package sy.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sy.dao.GonggaoDaoI;
import sy.model.Tgonggao;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.service.GonggaoServiceI;

import java.util.*;

@Service
public class GonggaoServiceImpl implements GonggaoServiceI {
	@Autowired
	private GonggaoDaoI gonggaoDao;
	
	@Override
	public void delete(String id) {
        gonggaoDao.delete(gonggaoDao.get(Tgonggao.class, id));
	}

	@Override
	public void add(Tgonggao tgonggao) throws Exception {
        Tgonggao u = new Tgonggao();
		u.setContent(tgonggao.getContent());
        u.setIsvailable(1);
        u.setTitle(tgonggao.getTitle());
		u.setId(UUID.randomUUID().toString());
        u.setCreatetime(tgonggao.getCreatetime());
		//u.settime(new Date());
        gonggaoDao.save(u);
	}
	
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	@Override
	public DataGrid dataGrid(Tgonggao user, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Tgonggao> ul = new ArrayList<Tgonggao>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tgonggao t ";
		List<Tgonggao> l = gonggaoDao.find(hql + whereHql(user, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tgonggao t : l) {
                Tgonggao u = new Tgonggao();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(gonggaoDao.count("select count(*) " + hql + whereHql(user, params), params));
		return dg;
	}

    @Override
    public void update(Tgonggao tgonggao){
        gonggaoDao.update(tgonggao);
    }

	private String whereHql(Tgonggao tad, Map<String, Object> params) {
		String hql = "";
		if (tad != null) {
			hql += " where 1=1 ";
			if (tad.getTitle() != null) {
				hql += " and t.title like :title";
				params.put("title", "%%" + tad.getTitle() + "%%");
			}

		}
		return hql;
	}

	@Override
    public List<Tgonggao> getTgonggaos(){
		
		String hql = " from Tgonggao t where t.isvailable = 1";
		List<Tgonggao> l = gonggaoDao.find(hql);
		
		return l;
	}
    @Override
    public Tgonggao get(String id){
        String hql = " from Tgonggao t where t.id = '"+id+"'";
        List<Tgonggao> l =gonggaoDao.find(hql);
        if(l.size()>0){
            return l.get(0);
        }else{
            return null;
        }

    }
}
